package net.xujialiang.XTestRPA.Service.Tenant;

import net.xujialiang.XTestRPA.Entity.Tenant.XRPATenant;
import net.xujialiang.XTestRPA.Entity.Tenant.XRPATenantOrder;
import net.xujialiang.XTestRPA.Repository.Tenant.TenantOrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class XRPATenantOrderService {
    @Autowired
    TenantOrderRepository orderRepository;

    /**
     * 创建订单信息
     * @param ttc 租户号
     * @param type 订单类型
     * @param amount 金额
     * @param note 描述
     * @throws Exception
     */
    public void createOrder(String ttc, String type, String amount, String note) throws Exception {
        XRPATenantOrder entity =  XRPATenantOrder
                .builder()
                .ttc(ttc)
                .type(type)
                .amount(amount)
                .note(note)
                .createTime(new Timestamp(System.currentTimeMillis()))
                .build();
        orderRepository.save(entity);
    }

    /**
     * 获取订单信息
     * @param page 页码
     * @param pageSize 每页数据条数
     * @return
     * @throws Exception
     */
    public Map<String, Object> fetchTenantOrderInfo(String ttc, int page, int pageSize) throws Exception {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest pr =  PageRequest.of(page,pageSize, sort);
        Page<XRPATenantOrder> pageData = orderRepository.findByTtc(ttc, pr);
        Map<String, Object> ret = new LinkedHashMap<>();
        ret.put("totalPages", pageData.getTotalPages());
        ret.put("totalCount", pageData.getTotalElements());
        ret.put("page", page);
        ret.put("pageSize", pageSize);
        ret.put("list", pageData.getContent());
        return ret;
    }

}
